package com.chatdating.controller;

import com.chatdating.entity.OrderInfo;
import com.chatdating.entity.pojo.Result;
import com.chatdating.service.AliPayService;
import com.chatdating.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;
    private final AliPayService aliPayService;

    @PostMapping("/create")
    public String createOrder(
            @RequestParam Long userId,
            @RequestParam String subject,
            @RequestParam BigDecimal amount,
            Model model
    ) {
        try {
            // 1. 创建订单
            OrderInfo order = orderService.createOrder(userId, subject, amount);

            // 2. 生成支付表单
            String paymentForm = aliPayService.createPayment(
                    order.getOrderNo(),
                    amount.doubleValue(),
                    subject
            );

            model.addAttribute("paymentForm", paymentForm);
            model.addAttribute("orderNo", order.getOrderNo());

            return "payment-form";
        } catch (Exception e) {
            model.addAttribute("error", "创建订单失败: " + e.getMessage());
            return "payment-error";
        }
    }

    @GetMapping("/payment-result")
    public String paymentResult(
            @RequestParam Map<String, String> alipayParams,
            @RequestParam(name = "out_trade_no") String orderNo,
            Model model) {

        // 1. 添加支付宝参数到模型（用于展示）
        model.addAttribute("alipayParams", alipayParams);

        try {
            // 2. 查询订单信息
            OrderInfo order = orderService.getOrderByNo(orderNo);

            if (order == null) {
                model.addAttribute("error", "订单不存在: " + orderNo);
                return "payment-error";
            }

            model.addAttribute("order", order);

            // 3. 根据状态显示不同页面
            if (order.getStatus() == 1) {
                // 已支付状态（可能是异步通知已处理）
                return "payment-success";
            } else if ("TRADE_SUCCESS".equals(alipayParams.get("trade_status"))) {
                // 支付宝返回成功但系统未处理（异步通知可能延迟）
                model.addAttribute("message", "支付成功！订单处理中，请稍后刷新页面...");
                return "payment-processing";
            } else {
                // 其他状态
                model.addAttribute("error", "支付状态异常: "
                        + alipayParams.get("trade_status"));
                return "payment-error";
            }
        } catch (Exception e) {
            model.addAttribute("error", "系统错误: " + e.getMessage());
            return "payment-error";
        }
    }
}
